package net.zoneland.zrdp.framework.web.service;

import javax.annotation.Resource;

import net.zoneland.zrdp.common.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import net.zoneland.zrdp.common.constant.CacheConstants;
import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.constant.UserConstants;
import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.common.core.domain.model.LoginUser;
import net.zoneland.zrdp.common.core.redis.RedisService;
import net.zoneland.zrdp.common.exception.ServiceException;
import net.zoneland.zrdp.common.exception.user.BlackListException;
import net.zoneland.zrdp.common.exception.user.CaptchaException;
import net.zoneland.zrdp.common.exception.user.CaptchaExpireException;
import net.zoneland.zrdp.common.exception.user.UserNotExistsException;
import net.zoneland.zrdp.common.exception.user.UserPasswordNotMatchException;
import net.zoneland.zrdp.common.utils.MessageUtils;
import net.zoneland.zrdp.common.utils.ip.IpUtils;
import net.zoneland.zrdp.framework.manager.AsyncManager;
import net.zoneland.zrdp.framework.manager.factory.AsyncFactory;
import net.zoneland.zrdp.framework.security.context.AuthenticationContextHolder;
import net.zoneland.zrdp.system.service.ISysConfigService;
import net.zoneland.zrdp.system.service.ISysUserService;

/**
 * 登录校验方法
 *
 * @author zonevue
 */
@Component
public class SysLoginService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SysLoginService.class);
    @Resource
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisService redisService;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysConfigService configService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(final String username, final String password, final String code, final String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);

        return commonLogin(username, password);
    }

    /**
     * sso登录验证
     *
     * @param username 用户名
     * @return 结果
     */
    public String ssoLogin(final String username) {
        return commonLogin(username, "sso");
    }

    /**
     * 登陆验证的通用方法
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    private String commonLogin(final String username, final String password) {

        // 用户验证
        try {
            final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            final Authentication authentication = authenticationManager.authenticate(authenticationToken);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            final LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            recordLoginInfo(loginUser.getUserId());
            // 生成token
            return tokenService.createToken(loginUser);
        } catch (final Exception e) {
            LOGGER.error("login error username:{} ", username, e);
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException("用户：" + username + "登录失败", e);
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(final String username, final String code, final String uuid) {
        final boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            final String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultIfEmpty(uuid, "");
            final String captcha = redisService.getCacheString(verifyKey);
            redisService.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }

            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(final String username, final String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        final String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(final Long userId) {
        final SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtil.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
